package com.xsir.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xsir.common.Result;
import com.xsir.dto.Author;
import com.xsir.dto.RegisterForm;
import com.xsir.entity.Article;
import com.xsir.entity.Collection;
import com.xsir.entity.User;
import com.xsir.service.IArticleService;
import com.xsir.service.ICollectionService;
import com.xsir.service.IUserService;
import com.xsir.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xsir
 * @date 2020/9/5
 * <p>
 * 用户表控制层
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    
    @Resource
    private IUserService userService;
    @Resource
    private IArticleService articleService;
    @Resource
    private ICollectionService collectionService;
    
    /**
     * 用户登录
     *
     * @param account  账号  必填
     * @param password 密码  必填
     * @return json: { token: token_str }
     */
    @RequestMapping("/login")
    @ResponseBody
    @Validated
    public Map<String, Object> login(@RequestParam("account") String account,
                                     @RequestParam("password") String password) {
        String token = userService.login(account, password, 0);
        Map<String, Object> data = new HashMap<>(1);
        data.put("token", token);
        data.put("code", 200);
        data.put("msg", "登录成功！");
        return data;
    }
    
    /**
     * 注册
     *
     * @param registerForm 注册表单对象
     * @return Result对象
     */
    @PostMapping("/register")
    @ResponseBody
    public Map<String, Object> register(@RequestBody RegisterForm registerForm) {
        Session session = SecurityUtils.getSubject().getSession(false);
        Map<String, Object> data = new HashMap<>(4);
        if (session == null) {
            data.put("message", "请先获取验证码");
            return data;
        }
        String code = (String) session.getAttribute(registerForm.getEmail());
        if (code == null) {
            data.put("message", "验证码已过期，请重新获取");
            return data;
        }
        if (!code.equals(registerForm.getCode())) {
            data.put("message", "验证码不正确");
            return data;
        }
        session.setTimeout(System.currentTimeMillis() - 1);
        
        String token = userService.register(registerForm);
        data.put("token", token);
        data.put("code", 200);
        data.put("msg", "登录成功！");
        return data;
    }
    
    /**
     * 退出：
     * 由于服务器不保存用户的状态，所以不用写/logout接口，
     * 前端删除保存的token即可
     */
    // @RequestMapping("/logout")
    // public void logout() {
    //     log.debug("执行退出！");
    // }
    
    /**
     * 重置密码
     *
     * @param account  账号【必填】
     * @param password 密码【必填】
     * @return json对象
     */
    
    public Result resetPassword(@RequestParam("account") String account,
                                @RequestParam("password") String password) {
        userService.resetPassword(account, password);
        return Result.ok();
    }
    
    /**
     * 获取作者信息
     */
    @RequestMapping("/author")
    public Result author(@RequestParam("author") String name) throws Exception {
        User user = userService.getOne(new QueryWrapper<User>().eq("username", name));
        if(user == null) {
            throw new Exception("用户不存在！");
        }
        Author author = new Author(user);
        // 获取发布的文章数
        author.setEssays(articleService.count(new QueryWrapper<Article>().eq("author_id", user.getId())));
        // author.setComments((long) commentService.count(new QueryWrapper<Comment>().eq("from_id", id)));
        author.setCollections(collectionService.count(new QueryWrapper<Collection>().eq("user_id", user.getId())));
        
        return Result.ok().data(author);
    }
    
    /**
     * 获取用户信息
     */
    @RequiresRoles("user")
    @RequestMapping("/info")
    public Result info(@RequestParam("token") String token) {
        String account = (String) JwtUtil.decode(token).get("account");
        User user = userService.getOne(new QueryWrapper<User>().eq("account", account));
        return Result.ok(user);
    }
    
    /**
     * 更新用户信息
     */
    @RequestMapping("/update")
    @RequiresRoles("user")
    public Result update(@RequestBody User user, HttpServletRequest request) {
        if (user == null) {
            return Result.error("参数为空！", 400);
        }
        log.debug(user.toString());
        String token = request.getHeader("Authorization");
        Integer uid = (Integer) JwtUtil.decode(token).get("uid");
        user.setId(Long.valueOf(uid));
        
        if (user.getPassword() != null && StringUtils.isEmpty(user.getPassword())) {
            String password = new SimpleHash("md5", user.getPassword(), user.getAccount()).toString();
            user.setPassword(password);
        }
        
        userService.updateById(user);
        return Result.ok();
    }
    
    @RequestMapping("/edit")
    @RequiresPermissions("admin")
    public Result edit() {
        return Result.ok("有权限操作！");
    }
}
